package com.jike.jkgame.data;

import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;

import com.jike.jkgame.Utilis;
import com.jike.jkgame.db.ResourcesDAO;

public class General {
	public int id;
	public String name;
	public String description;
	public byte star_level;
	public byte country;
	public int attack;
	public byte attack_range;
	public int defense;
	public byte defense_range;
	public int attack_addon;
	public int defense_addon;
	public int[] skillIds;
	
	public Skill[] skills;
	
	
	private static General parseGeneral(DataInputStream dis, byte[] buff) {
		General g = new General();
		try {
			g.id = dis.readInt();
			g.name = Utilis.getString(dis, buff);
			g.description = Utilis.getString(dis, buff);
			g.star_level = dis.readByte();
			g.country = dis.readByte();
			g.attack = dis.readInt();
			g.attack_range = dis.readByte();
			g.defense = dis.readInt();
			g.defense_range = dis.readByte();
			g.attack_addon = dis.readInt();
			g.defense_addon = dis.readInt();
			
			int cnt = dis.readInt();
			g.skillIds = new int[cnt];
			for(int i=0; i<cnt; ++i) {
				g.skillIds[i] = dis.readInt();
			}
			
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
		
		return g;
	}
	
	public static int parseDataFile(InputStream in) {
		DataInputStream dis = new DataInputStream(in);
		int count  = 0;
		
		ResourcesDAO dao = ResourcesDAO.get();
		byte[] buff = new byte[4096];
		
		try {
			int type = dis.readInt();
			int version = dis.readInt();
			
			int myVersion = dao.getDataFileVersion(type);
			
			if (myVersion >= version) {
				return 0;
			}
			
			dao.clearGenerals();
			General g = null;
			do {
				g = parseGeneral(dis, buff);
				dao.insertGeneral(g);
			}while(g != null);
			dao.updateDataFileVersion(type, version);
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		
		return count;
	}

}
